import readWrite.readWriteHelper;
import Jama.Matrix;
import matrixCalculator.MatrixHelper;


//this class the worker class that will parse the message, create the matrix and execute the operation.
public class ThreadPerConnection {
	
	String request;
	int N=0;
	String Operator="";
	long processTime=0;
	long readWriteTime=0;

	public ThreadPerConnection (String message){
		this.request = message;
		parseMsg();
	}
	
	public void parseMsg(){
		String [] arrayAux= request.split("_");
		if(arrayAux[0]!= null)this.N=Integer.parseInt(arrayAux[0]);
		if(arrayAux[1]!= null)this.Operator=arrayAux[1];
	}
	
	public Matrix doOperation(Matrix matrixA, Matrix matrixB){
		Matrix matrixR=null;
		if(this.Operator.equals("+")){
			matrixR=MatrixHelper.sumMatrix(matrixA, matrixB);
		}else if(this.Operator.equals("-")){
			matrixR=MatrixHelper.subsMatrix(matrixA, matrixB);
		}else if(this.Operator.equals("*")){
			matrixR=MatrixHelper.multiplyMatrix(matrixA, matrixB);
		}else if(this.Operator.equals("/")){
			matrixR=MatrixHelper.divideMatrix(matrixA, matrixB);
		}
		return matrixR;
	}
	
	/**This class keeps a thread-like structure but is not actually a thread.
	In the run method the matrixes are created and the operation is executed.**/
	public String run(){
		String answer="";
		System.out.println("Requesting a " + this.N +" Matrix. Operation " + this.Operator );
		long processInit=System.currentTimeMillis();
		
		//Creating the matrixes
		Matrix A=MatrixHelper.generateMatrix(this.N);
		Matrix B=MatrixHelper.generateMatrix(this.N);
		long processEnd=System.currentTimeMillis();
		this.processTime=processEnd-processInit;
	
		long readWriteInit=System.currentTimeMillis();

		
		readWriteHelper.writeFile("test/matrixA.txt", A);
		readWriteHelper.writeFile("test/matrixB.txt", B);
		Matrix A_=readWriteHelper.readFile2("test/matrixA.txt");
		Matrix B_=readWriteHelper.readFile2("test/matrixB.txt");
		
		long readWriteEnd=System.currentTimeMillis();
		this.readWriteTime=readWriteEnd-readWriteInit;

		processInit=System.currentTimeMillis();
		
		//executing Operation
		Matrix R=doOperation(A_, B_);
		processEnd=System.currentTimeMillis();
		this.processTime+=(processEnd-processInit);
		readWriteInit=System.currentTimeMillis();

		
		readWriteHelper.writeFile("test/matrixR.txt", R);
		String R_=readWriteHelper.readFile("test/matrixR.txt");
		readWriteEnd=System.currentTimeMillis();
		this.readWriteTime+=(readWriteEnd-readWriteInit);
		
		//creating answer
		answer= (this.N + "_" + this.Operator + "\n" +"rwTime_"+this.readWriteTime + "\n" + "pTime_"+this.processTime + "\n" + R_ + "\n");
		

		return answer;
	}
	
}
